package com.usian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.pojos.Department;
import com.usian.pojos.Employee;
import com.usian.service.DepartmentService;
import com.usian.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/toadd")
    public String toadd(HttpSession session){

        Employee employee = (Employee)session.getAttribute("employee");

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(Employee::getEname,employee.getEname());

        Employee one = employeeService.getOne(wrapper);

        if (one.getQuanxian().equals("1")){

            return "addDepartment";
        }else {
            return null;
        }
    }

    @GetMapping("/toupdate")
    public String toupdate(HttpSession session,Integer id,Model model){

        Employee employee = (Employee)session.getAttribute("employee");

        QueryWrapper<Employee> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(Employee::getEname,employee.getEname());

        Employee one = employeeService.getOne(wrapper);

        if (one.getQuanxian().equals("1")){

            Department department = departmentService.getById(id);

            model.addAttribute("d",department);

            return "updateDepartment";
        }else {
            return null;
        }
    }

    @GetMapping("/findDepartment")
    public String findDepartment(Model model, HttpSession session){

        List<Department> department = departmentService.findDepartment();

        model.addAttribute("department",department);

        return "department";
    }

    @PostMapping("/addDepartment")
    public String addDepartment( Department department){

        departmentService.addDepartment(department);

        return "redirect:department/findDepartment";
    }

    @PostMapping("/updateDepartment")
    public String updateDepartment( Department department){

        departmentService.updateDepartment(department);

        return "redirect:department/findDepartment";
    }

    @GetMapping("/delDepartment")
    public String del(Integer id){

        departmentService.delDepartment(id);

        return "redirect:department/findDepartment";
    }
}
